#!/bin/bash

TS_TOPDIR="${0%/*}/../.."
TS_DESC="drop page caches related to a file"

. "$TS_TOPDIR"/functions.sh
ts_init "$*"

ts_check_test_command "$TS_CMD_FADVISE"
ts_check_test_command "$TS_CMD_FINCORE"
ts_check_test_command "$TS_CMD_FINDMNT"

ts_check_prog "dd"
ts_check_prog "sleep"

ts_cd "$TS_OUTDIR"

FILE="ddtest"
BS=65536
COUNT=8

FS="$("$TS_CMD_FINDMNT" -nr -o FSTYPE -T "$PWD")"
if [[ "$FS" = "tmpfs" || "$FS" = "overlay" || "$FS" = "" ]]; then
	ts_skip "fincore does not work on tmpfs or unknown fs"
fi

create_file() {
    dd if=/dev/zero of="$FILE" bs=$BS count=$COUNT conv=fsync >& /dev/null
}

do_fincore() {
    "$TS_CMD_FINCORE" -o RES,SIZE,FILE "$FILE"
}

{
    create_file
    do_fincore
    echo

    create_file
    echo "whole file"
    "$TS_CMD_FADVISE" "$FILE"
    echo status: $?
    do_fincore
    echo

    create_file
    echo "offset: $(( 2 * $BS ))"
    "$TS_CMD_FADVISE" -o $(( 2 * $BS )) "$FILE"
    echo status: $?
    do_fincore
    echo

    create_file
    echo "length: $(( 4 * $BS ))"
    "$TS_CMD_FADVISE" -l $(( 4 * $BS )) "$FILE"
    echo status: $?
    do_fincore
    echo

    create_file
    echo "offset: $(( 2 * $BS )), length: $(( 4 * $BS )) fd: 42"
    "$TS_CMD_FADVISE" -o $(( 2 * $BS )) -l $(( 4 * $BS )) --fd 42 42<"$FILE"
    echo status: $?
    do_fincore
    echo

    rm "$FILE"
} >> "$TS_OUTPUT" 2>> "$TS_ERRLOG"

ts_finalize
